<template>
  <div class="order-list">
    <h2>我的订单</h2>
    <table v-if="orders.length">
      <thead>
        <tr>
          <th>订单号</th>
          <th>课程</th>
          <th>金额</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="order in orders" :key="order.id">
          <td>{{ order.id }}</td>
          <td>{{ order.courseId }}</td>
          <td>¥ {{ order.amount }}</td>
          <td>{{ getStatusText(order.status) }}</td>
          <td>
            <button @click="refundOrder(order.id)" v-if="order.status === 'PAID'">
              退款
            </button>
          </td>
        </tr>
      </tbody>
    </table>
    <p v-else>暂无订单</p>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { paymentService, PaymentOrder } from '@/services/payment.service'

const orders = ref<PaymentOrder[]>([])

onMounted(async () => {
  try {
    orders.value = await paymentService.getPaymentHistory('current_user_id')
  } catch (error) {
    console.error('获取订单失败', error)
  }
})

const getStatusText = (status: string) => {
  const statusMap = {
    'PENDING': '待支付',
    'PAID': '已支付',
    'FAILED': '支付失败'
  }
  return statusMap[status] || status
}

const refundOrder = async (orderId: string) => {
  try {
    await paymentService.refundOrder(orderId)
    orders.value = orders.value.filter(order => order.id !== orderId)
  } catch (error) {
    console.error('退款失败', error)
  }
}
</script>

<style scoped>
.order-list {
  padding: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 5px 10px;
}
</style>